package com.kly.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.kly.user.config.NacosValueConfig;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.dto.TrafficSourceDto;
import com.kly.user.dto.vo.TrafficSourceReq;
import com.kly.user.enums.AppCodeEnum;
import com.kly.user.enums.TrafficSourceEnum;
import com.kly.user.service.AsyncSendMsgService;
import com.kly.user.service.RCClient;
import com.kly.user.service.UserTrafficSourceService;
import com.kly.user.service.WhiteListService;
import com.kly.user.serviceImpl.dto.MsgSender;
import io.rong.messages.TxtMessage;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service("asyncSendMsgService")
public class AsyncSendMsgServiceImpl implements AsyncSendMsgService {

    @Resource
    RCClient rcClient;
    @Resource
    private UserDao userDao;
    @Resource
    private WhiteListService whiteListService;
    @Resource
    NacosValueConfig nacosValueConfig;
    @Resource
    UserTrafficSourceService userTrafficSourceService;

    @Override
    public String getSender(String appCode) {
        appCode = StringUtils.isEmpty(appCode) ? AppCodeEnum.MEBOO.getAppCode() : appCode;
        final Map<String, MsgSender> msgSender = nacosValueConfig.getMsgSender();
        return msgSender.get(appCode).getAccount();
    }

    @Override
    @Async("taskExecutor")
    public void sendMsg(String appCode, String targetId, String objectName, String content, String pushContent) {
        // 如果是服务(meboo,pp)消息，则需判断接收方是否白名单
//        if ("1113913307465977856".equals(currentUserId)) {
//            UserEntity user = userDao.selectByUserCode(targetId);
//            // 注意：外部调用发送消息接口时，存在用户注销的情况
//            if (user == null) {
//                log.info("AsyncSendMsgService:user {} not found. {}", targetId, currentUserId);
//                return;
//            }
//            //【meboo-v3.1.3】加入【加白账号库】的账号，不会收到系统通知
//            log.info("AsyncSendMsgService:sendMsg starts. {},{}", currentUserId, targetId);
//            Response<Boolean> inWhiteList = whiteListService.in(user.getAppCode(), user.getUserCode(), user.getMobile(), user.getEmail());
//            log.info("AsyncSendMsgService:sendMsg ends. {},{},{}", currentUserId, targetId, JSON.toJSON(inWhiteList));
//            if (inWhiteList.getData()) {
//                log.info("User {} is in white-list.No need send service-msg.", targetId);
//                return;
//            }
//        }

        final UserEntity user = userDao.selectByUserCode(targetId);
        final Response<TrafficSourceDto> trafficSourceResp = userTrafficSourceService.getTrafficSource(TrafficSourceReq.buildReq(user.getAppCode(), user.getUserCode(), user.getMobile(), user.getEmail(), null));
        final TrafficSourceDto trafficSourceDto = trafficSourceResp.getData();

        if (TrafficSourceEnum.None_Organic.getType() == trafficSourceDto.getTrafficSourceEnum().getType()
            || TrafficSourceEnum.All.getType() == trafficSourceDto.getTrafficSourceEnum().getType()) {

            PrivateMessage privateMessage = new PrivateMessage()
                    .setSenderId(getSender(appCode))
                    // 是否向发件人客户端同步已发消息。1 表示同步 0，即不同步
                    .setIsIncludeSender(1)
                    .setTargetId(new String[]{targetId})
                    .setObjectName(objectName)
                    .setContent(new TxtMessage(content, ""))
                    .setPushContent(pushContent);
            ResponseResult responseResult = rcClient.sendPrivateMessage(privateMessage);
            log.info("AsyncSendMsgServiceImpl.sendMsg:{}", JSONObject.toJSONString(privateMessage));
            if (Objects.nonNull(responseResult) && responseResult.getCode() == 200) {
                log.info("sendMsg success");
            }
        }
    }


}
